aboutsummaryrefslogtreecommitdiff
path: root/src/app/(main)/websites/[websiteId]/(reports)/utm/UTM.tsx
blob: 1399174a1394150e51ccdb460a4810b437004e5f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { Column, Grid, Heading, Text } from '@umami/react-zen';
import { PieChart } from '@/components/charts/PieChart';
import { LoadingPanel } from '@/components/common/LoadingPanel';
import { Panel } from '@/components/common/Panel';
import { useMessages, useResultQuery } from '@/components/hooks';
import { ListTable } from '@/components/metrics/ListTable';
import { CHART_COLORS, UTM_PARAMS } from '@/lib/constants';

export interface UTMProps {
  websiteId: string;
  startDate: Date;
  endDate: Date;
}

export function UTM({ websiteId, startDate, endDate }: UTMProps) {
  const { formatMessage, labels } = useMessages();
  const { data, error, isLoading } = useResultQuery<any>('utm', {
    websiteId,
    startDate,
    endDate,
  });

  return (
    <LoadingPanel data={data} isLoading={isLoading} error={error} minHeight="300px">
      {data && (
        <Column gap>
          {UTM_PARAMS.map(param => {
            const items = data?.[param];

            const chartData = {
              labels: items.map(({ utm }) => utm),
              datasets: [
                {
                  data: items.map(({ views }) => views),
                  backgroundColor: CHART_COLORS,
                  borderWidth: 0,
                },
              ],
            };
            const total = items.reduce((sum, { views }) => {
              return +sum + +views;
            }, 0);

            return (
              <Panel key={param}>
                <Grid columns={{ xs: '1fr', md: '1fr 1fr' }} gap="6">
                  <Column>
                    <Heading>
                      <Text transform="capitalize">{param.replace(/^utm_/, '')}</Text>
                    </Heading>
                    <ListTable
                      metric={formatMessage(labels.views)}
                      data={items.map(({ utm, views }) => ({
                        label: utm,
                        count: views,
                        percent: (views / total) * 100,
                      }))}
                    />
                  </Column>
                  <Column>
                    <PieChart type="doughnut" chartData={chartData} />
                  </Column>
                </Grid>
              </Panel>
            );
          })}
        </Column>
      )}
    </LoadingPanel>
  );
}